<template>
  <div>
    <div class="hx_cropper">
      <div class="hx_cropper_title">
        <p>选择图片：</p>
        <label class="btn" for="uploads">选择图片</label>
        <input type="file" id="uploads" style="position: absolute; clip: rect(0 0 0 0)" accept="image/png, image/jpeg, image/gif, image/jpg" @change="selectImg($event)" />
      </div>
    </div>

    <div class="">
      <div class="cropper_display">
        <div class="cropper-content">
          <div class="cropper-box">
            <div class="cropper">
              <vue-cropper ref="cropper" :img="option.img" :outputSize="option.outputSize" :outputType="option.outputType" :info="option.info" :canScale="option.canScale" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :fixed="option.fixed" :fixedNumber="option.fixedNumber" :full="option.full" :fixedBox="option.fixedBox" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :centerBox="option.centerBox" :height="option.height" :infoTrue="option.infoTrue" :maxImgSize="option.maxImgSize" :enlarge="option.enlarge" :mode="option.mode" @realTime="realTime" @imgLoad="imgLoad">
              </vue-cropper>
            </div>
          </div>
        </div>
        <div class="cropper_size">
          <p>系统自动剪裁合适的大小尺寸</p>
          <el-radio-group v-model="sizeValue" disabled>
            <el-radio v-for="(item, index) in sizeOptions" :key="index" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>

          <div class="upload-btn">
            <el-button size="mini" type="success" @click="uploadImg">保存裁剪 <i class="el-icon-upload"></i></el-button>
          </div>
        </div>
      </div>
    </div>

<!--    <div class="list_title">-->
<!--      素材库-->
<!--      <em>*素材库只默认保存3个月内上传过的图片记录，超过三个月的素材将自动删除</em>-->
<!--    </div>-->
<!--    <ul class="list_wrap">-->
<!--      <li v-for="(item, index) in list" :key="index" :class="['list_item', { active: index == active }]" @click="handleImgClick(item, index)">-->
<!--        <img class="images" :src="ftpDownload + item.pictureFtp" alt="" />-->
<!--      </li>-->
<!--    </ul>-->
<!--    <div class="fenye">-->
<!--      <el-pagination background :current-page.sync="searjuery.page" :page-size="searjuery.pageSize" layout="prev, pager, next, jumper" :total="searjuery.total" @current-change="handleCurrentChange" />-->
<!--    </div>-->
    <div slot="footer" align="center">
      <el-button :disabled="isdis" type="primary" @click="save">保存</el-button>
      <el-button @click="cancel" v-if="isshow">返回</el-button>
    </div>
  </div>
</template>

<script>
const axios = require("axios");
import { VueCropper } from "vue-cropper";
import BcUpload from "@/components/BcUpload/index";
import { getOnceTokenFn } from "@/api/getOnceToken";
import { getToken, getFtpCs, getFtpCk } from "@/utils/auth";
export default {
  name: "picUpload",
  components: { BcUpload, VueCropper },
  props: {
    picDialog: {
      type: Object,
      default() {
        return {};
      },
    },
    piclx: {
      type: Number,
      default: 0,
    },
    Secondary: {
      type: Number,
      default: 0,
    },
    isshow: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    picDialog: {
      handler: function (val) {
        console.log(123, val);
        this.picDialog = val;
        this.chushihua();
      },
      deep: true,
      immediate: true,
    },
    isshow: {
      handler: function (val) {
        console.log(val);
        this.isshow = val;
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      previews: {},
      option: {
        img: "", //裁剪图片的地址
        outputSize: 1, //裁剪生成图片的质量(可选0.1 - 1)
        outputType: "jpeg", //裁剪生成图片的格式（jpeg || png || webp）
        info: true, //图片大小信息
        canScale: false, //图片是否允许滚轮缩放
        autoCrop: true, //是否默认生成截图框
        autoCropWidth: 750, //默认生成截图框宽度
        // autoCropHeight: 150, //默认生成截图框高度
        fixed: true, //是否开启截图框宽高固定比例
        fixedNumber: [], //截图框的宽高比例
        full: true, //false按原比例裁切图片，不失真
        fixedBox: false, //固定截图框大小，不允许改变
        canMove: false, //上传图片是否可以移动
        canMoveBox: true, //截图框能否拖动
        original: false, //上传图片按照原始比例渲染
        centerBox: false, //截图框是否被限制在图片里面
        height: true, //是否按照设备的dpr 输出等比例图片
        infoTrue: true, //true为展示真实输出图片宽高，false展示看到的截图框宽高
        maxImgSize: 3000, //限制图片最大宽度和高度
        enlarge: 1, //图片根据截图框输出比例倍数
        // mode: "100% auto", //图片默认渲染方式
      },
      active: -1,
      ftpDownload: this.$store.getters.ftpInfo
        ? this.$store.getters.ftpInfo.download
        : "http://172.16.1.54:3001",
      list: [],
      searjuery: {
        total: 0,
        page: 1,
        pageSize: 14,
        pictureLx: "",
      },
      sizeOptions: [
        {
          label: "头像（1：1）",
          value: 1,
        }
      ],
      sizeValue: "",
      isdis: true,
      // ftpUpload:'',
      ftpUpload: this.$store.getters.ftpInfo
        ? this.$store.getters.ftpInfo.upload
        : "http://172.16.1.54:3000/",
    };
  },
  methods: {
    chushihua(Secondary) {
      this.sizeValue = this.piclx;
      this.option.fixedNumber = [4, 3]
      if(this.piclx == 1){
        this.option.fixedNumber = [1, 1];
      }
      this.searjuery.pictureLx = this.piclx;
    },
    //初始化函数
    imgLoad(msg) {
      // console.log("工具初始化函数=====" + msg);
    },
    //实时预览函数
    realTime(data) {
      this.previews = data;
    },
    //选择图片
    selectImg(e) {

      let file = e.target.files[0];
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: "图片类型要求：jpeg、jpg、png",
          type: "error",
        });
        return false;
      }
      let reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.option.img = data;
      };
      //转化为base64
      reader.readAsDataURL(file);
    },
    // base64 => file
    base64ToFile(base64, fileName) {
      let arr = base64.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]);
      let n = bytes.length;
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
    },
    //上传图片
    uploadImg(type) {

      this.$refs.cropper.getCropData((data) => {
        let r = this.base64ToFile(data, "jpg");
        const xhr = new XMLHttpRequest();
        const param = new FormData();
        param.append("ftpFileToDiskPath", "ccjc");
        param.append("file", r);
        const config = {
          headers: { "Content-Type": "multipart/form-data" },
        };

        config.headers["userToken"] = getToken();

        xhr.open("post", this.ftpUpload + "uploadMany", true);
        xhr.send(param);
        console.log('params',param)
        xhr.onreadystatechange = () => {
          if (xhr.status == 200 && xhr.readyState == 4) {
            this.$message.success("裁剪成功，请保存！");
            this.isdis = false;
            let res = JSON.parse(xhr.response);
            this.picDialog.path = res.files[0].path;
            let picdata = {
              pictureLx: this.piclx,
              pictureFtp: res.files[0].path,
            };
            // pictureVOinsert(picdata).then((res) => {
            //   if (res.flag) {
            //     console.log("成功上传到素材库", res);
            //   }
            // });
          }
        };
      });
    },
    uploadChange() {
      this.active = -1;
    },
    picDialogBtn() {
      this.$refs.picDialogUpload.$refs.imageInput.click();
    },
    /**图片地址转base64 */
    getBase64(url) {
      let _this = this;
      var Img = new Image(),
        dataURL = "";
      Img.src = url + "?v=" + Math.random();
      Img.setAttribute("crossOrigin", "Anonymous");
      Img.onload = function () {
        var canvas = document.createElement("canvas"),
          width = Img.width,
          height = Img.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").translate(0.5,0.5)
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height);
        dataURL = canvas.toDataURL("png");
        _this.picChange(dataURL);
        console.log(dataURL);
      };
      return dataURL;
    },
    picChange(url) {
      let r = this.base64ToFile(url, "file");
      let reader = new FileReader();
      this.option.img = url;
      reader.readAsDataURL(r);
    },
    handleImgClick(item, index) {
      this.getBase64(this.ftpDownload + item.pictureFtp);
    },
    cshimgurl() {
      this.option.img = "";
      var file = document.getElementById("uploads");
      file.value = "";
    },
    save() {
      if (!this.picDialog.path) {
        this.$message.error("请先保存裁剪的图片");
        return;
      }
      console.log('this.ftpUpload=='+this.ftpUpload)
      console.log('ftpDownload--'+this.ftpDownload)
      console.log('picDialog.path--'+this.picDialog.path)
      this.$emit("save", this.picDialog.path);
    },
    cancel() {
      this.picDialog.visible = false;
      this.cshimgurl();
    },
    // getPicList(data) {
    //   selectFtpList(data).then((res) => {
    //     if (res.data.items instanceof Array) {
    //       this.list = res.data.items;
    //       this.searjuery.total = res.data.total;
    //     }
    //   });
    // },
    // handleCurrentChange(val) {
    //   this.searjuery.page = val;
    //   console.log(val);
    //   this.getPicList(this.searjuery);
    // },
  },
  created() {
    // 1春城驿家管理 2关爱服务管理 3志愿服务管理 4小程序首页图/微心图
    this.chushihua();
  },
};
</script>

<style scoped lang="scss">
.hx_cropper_title {
  display: flex;
  p {
    line-height: 36px;
  }
  .btn {
    padding: 10px 20px;
    font-size: 14px;
    border-radius: 4px;
    color: #ffffff;
    background-color: #1890ff;
    border-color: #1890ff;
  }
}

.cropper-content {
  margin-top: 20px;
  width: 750px;
  .cropper-box {
    flex: 1;
    width: 100%;
    .cropper {
      width: auto;
      height: 300px;
    }
  }

  .show-preview {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    .preview {
      overflow: hidden;
      border: 1px solid #67c23a;
      background: #cccccc;
    }
  }
}
.footer-btn {
  margin-top: 30px;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  .scope-btn {
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    padding-right: 10px;
  }
  .upload-btn {
    flex: 1;
    -webkit-flex: 1;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
  }
  .btn {
    outline: none;
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    -webkit-appearance: none;
    text-align: center;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    outline: 0;
    -webkit-transition: 0.1s;
    transition: 0.1s;
    font-weight: 500;
    padding: 8px 15px;
    font-size: 12px;
    border-radius: 3px;
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    margin-right: 10px;
  }
}
.upload_title {
  color: #16163a;
  font-size: 16px;
  font-weight: bold;
  padding-bottom: 20px;

  i {
    color: #ff3131;
  }
}

.btn_wrap {
  display: flex;
  align-items: center;

  .btn_box {
    cursor: pointer;
    width: 290px;
    height: 80px;
    background: rgba(243, 246, 255, 0.39);
    border: 1px dashed #335dff;
    border-radius: 8px;
    display: flex;
    align-items: center;

    img {
      margin: 0 20px;
    }

    .text_first {
      font-size: 16px;
      font-weight: bold;
      line-height: 30px;
      color: #16163a;
    }

    .text_second {
      font-size: 14px;
      line-height: 20px;
      color: #a9a9a9;
    }
  }
}

.pic_name {
  font-size: 16px;
  color: #335dff;
  padding-left: 35px;
}

.down_text {
  font-size: 14px;
  line-height: 40px;
  color: #ff3131;
}

.list_title {
  font-size: 16px;
  font-weight: bold;
  color: #16163a;
  line-height: 40px;
  padding: 10px 0;
}

.scroll_wrap {
  margin: 20px 0;

  ::v-deep.el-scrollbar__wrap {
    overflow-x: hidden !important;
  }
}

.list_wrap {
  display: flex;
  flex-wrap: wrap;

  .list_item {
    cursor: pointer;
    width: calc((100% - 60px) / 7);
    margin-right: 10px;
    border: 1px #ebebeb solid;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 10px;

    &:hover {
      border-color: #46a6ff;
    }
    &:nth-child(7n) {
      margin-right: 0;
    }

    .images {
      // width: 100%;
      // height: 144px;
      max-height: 100%;
      max-width: 100%;
    }
  }

  .active {
    border-color: #46a6ff;
  }
}
.cropper_display {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
.cropper_size {
  width: calc(100% - 770px);
  margin-top: 20px;
  p {
    padding-bottom: 20px;
  }
  .el-radio {
    display: block;
    padding-bottom: 10px;
  }
}
</style>
